<?php

namespace app\api\controller;

use app\api\model\Common;
use app\BaseController;
use Exception;
use frame\lib\Captcha;
use frame\lib\Db;
use frame\lib\VerfiyParam;

class Register extends BaseController
{
    // 二级用户注册方法
    public function do()
    {
        $param = $_POST;
        $conf = Common::verifyConf($param);
        $rule = ['username|用户名' => 'require|min:6|max:12', 'password|密码' => 'require|min:6|max:12', 'email|邮箱' => 'require|email', 'user_id' => 'require|int'];
        VerfiyParam::init($param, $rule);
        if ($conf['is_reg'] != 1) error('当前App已关闭注册');

        $ip = ip();
        $sql = "select max(id) as id from user where ip = '{$ip}';";
        $limitReg = Db::queryOne($sql);
        $limitReg =  Db::name('user')->where(['id' => $limitReg['id']])->find();
        if (date('d', getTime(3, @$limitReg['create_time'])) == date('d', time())) error('一个IP每天只能注册一个账户哦 !');

        $username = $param['username'];
        $hasUser = Db::name('user')->where(['username' => $username, 'role' => 2, 'user_id' => $param['user_id']])->find();
        if ($hasUser) error('已存在该用户名，请更换另一个！');
        $password = $param['password'];
        $email = $param['email'];
        $data = [
            'username' => $username,
            'password' => encrypt_pwd($password),
            'email' => $email,
            'role' => 2,
            'status' => 1,
            'create_time' => getTime(),
            'ip' => ip(),
            'user_id' => $param['user_id'],
        ];
        $res = Db::name('user')->insert($data);
        $score = $conf['reg_send_score'];
        $vip_time = date('Y-m-d H:i:s', time() + $conf['reg_vip_time']);
        $lastUser = Db::queryOne("select max(id) as id from user;");
        if ($res) {
            Db::name('user')->where(['id' => $lastUser])->update(['score' => $score, 'vip_time' => $vip_time]);
            success();
        }
        error();
    }
}
